package cn.tiancaifan.web;

import cn.tiancaifan.entity.SystemResult;
import cn.tiancaifan.service.UserServiceI;
import cn.tiancaifan.service.impl.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {

    private UserServiceI userService = new UserServiceImpl();

    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        requestError(resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        requestError(resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        requestError(resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/json;charset=utf-8");
        //获取前端传来的参数
        String account = req.getParameter("account");
        String password = req.getParameter("password");

        SystemResult register = userService.register(account, password);
        HttpSession session = req.getSession();
        session.setAttribute("user",register.getData());

        String s = gson.toJson(register);
        System.out.println(s);
        //输出
        PrintWriter out = resp.getWriter();
        out.println(s);

    }

    public void requestError(HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        SystemResult error = SystemResult.error("请求出错！");
        String s = gson.toJson(error);
        out.println(s);
    }
}
